import { defineStore } from "pinia";
import { loginApi, logoutApi, userInfoApi } from "@/apis/user";
import { setToken, clearToken } from "@/utils/auth";
import { removeRouteListener } from "@/utils/route-listener";
import useAppStore from "../app";

const useUserStore = defineStore("user", {
  state: () => ({
    user: {
      userId: undefined,
      userName: undefined,
      nickName: undefined,
      userType: undefined,
      phonenumber: undefined,
      email: undefined,
      avatar: undefined,
      remark: undefined,
      deptId: undefined,
      dept: undefined,
      loginIp: undefined,
    },
    role: undefined,
    permission: [],
  }),

  getters: {
    userInfo(state) {
      return { ...state.user };
    },
  },

  actions: {
    // Set user's information
    setInfo(partial) {
      this.$patch(partial);
    },

    // Reset user's information
    resetInfo() {
      this.$reset();
    },

    // Get user's information
    async info() {
      const res = await userInfoApi();
      console.log(res.data);
      this.setInfo(res.data);
    },

    // Login
    async login(loginForm) {
      try {
        const res = await loginApi(loginForm);
        console.log(res);
        setToken(res.data.token);
      } catch (err) {
        clearToken();
        throw err;
      }
    },
    logoutCallBack() {
      const appStore = useAppStore();
      this.resetInfo();
      clearToken();
      removeRouteListener();
    },
    // Logout
    async logout() {
      try {
        await logoutApi();
      } finally {
        this.logoutCallBack();
      }
    },
  },
});

export default useUserStore;
